<template>
  <div class="page-module">
    <div class="flex flex-wrap">
      <div
        v-for="(item, index) in props.list"
        :key="item.id"
        class="card w-[196px] h-[267px] rounded-[4px] flex flex-col p-[8px] box-sizing justify-between mr-[45px] mb-[44px]"
        :class="{ activeCss: activeIndex == index }"
        @click="chooseTemplate(item, index)"
      >
        <div class="w-[180px] h-[180px] mb-[8px]">
          <img src="@/assets/icon/template.jpg" class="w-[180px] h-[180px] rounded-[4px]" alt="" srcset="" />
        </div>
        <div class="text-[16px] text-[#262626] font-medium mb-[8px] truncate">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ item.name }}
            </template>
            <div class="ellipsis-text">
              {{ item.name || '-' }}
            </div>
          </a-tooltip>
        </div>
        <div class="text-[12px] h-[20px] text-[#8C8C8C] font-medium mb-[8px] flex justify-between">
          <div>
            {{ getLastTimeStr(formatToDateTime(item.updated_at * 1000), true) }}
          </div>
          <a-popover overlayClassName="menu-popover" placement="rightTop" autoAdjustOverflow>
            <template #content style="cursor: pointer">
              <div @click="handlePreview(item)">预览</div>
              <div @click="createCopy(item)">创建副本</div>
              <div @click="handleEdit(item.id)">编辑</div>
              <div @click="onlineEdit(item.id)">在线编辑</div>
              <div @click="deleteTemplate(item)">删除</div>
            </template>
            <div class="preview w-[24px] h-[24px] rounded-[4px] bg-[#E4F0FC] text-[#0083FF] cursor-pointer">
              <ellipsis-outlined class="text-[14px]" />
            </div>
          </a-popover>
        </div>
      </div>
    </div>
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该模板吗</span>
    </modal-view>
    <!-- 创建副本 -->
    <modal-view
      title="创建副本"
      v-model:visible="createVisible"
      okText="确定"
      cancelText="取消"
      :width="644"
      :afterClose="handleEditClose"
      @confirm="createConfirm"
      @cancel="createCancel"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules">
        <a-form-item label="模板名称" name="name">
          <a-input
            v-model:value.trim="formState.name"
            :maxlength="30"
            class="input-m-r-16 w-[492px]"
            placeholder="请输入模板名称（30个字以内）"
          />
        </a-form-item>
      </a-form>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { formatToDateTime, getLastTimeStr } from '@/utils/format'
import ModalView from '@/components/components/modal/ModalView.vue'
import type { TemplateItem } from '@/types/template/published'
import { reactive, ref } from 'vue'
import { JUMP_URL } from '../../state'
import apis from '@/apis'
import { message } from 'ant-design-vue'
import { storage } from '@/utils/storage'
import router from '@/router'
const {
  template: { published_delete, published_create }
} = apis
const emit = defineEmits(['update-list'])
interface SiteData {
  type: number
  list: any[]
}
const props = defineProps<SiteData>()
const formRef = ref()
const deleteVisible = ref(false)
const createVisible = ref(false)
const deleteId = ref()
const activeIndex = ref()
const chooseTemplate = (item: any, index: number) => {
  activeIndex.value = index
}
interface IFormState {
  name: string | undefined
  style_name: string | undefined
  type: number | undefined
  video_site_id: string | undefined
  article_site_id: string | undefined
  picture_site_id: string | undefined
  adv_lib_id: string | undefined
  publish_status: number | undefined
}
const formState = reactive<IFormState>({
  name: undefined,
  style_name: undefined,
  type: undefined,
  video_site_id: undefined,
  article_site_id: undefined,
  picture_site_id: undefined,
  adv_lib_id: undefined,
  publish_status: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '请输入模板名称（30个字以内）' }]
})
//编辑
const handleEdit = (id: string) => {
  router.push({ name: 'EditTemplate', query: { id } })
}
//在线编辑
const onlineEdit = (id: string) => {
  const token = storage.get('token')
  window.open(`${JUMP_URL}?token=${token}&id=${id}`, '_blank')
}
//删除
const deleteTemplate = (record: TemplateItem) => {
  deleteVisible.value = true
  deleteId.value = record.id
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  published_delete({ id: deleteId.value }).then(() => {
    deleteVisible.value = value
    message.success('删除成功')
    emit('update-list')
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
//预览
const handlePreview = (item: TemplateItem) => {
  console.log('item: ', item)
  router.push({
    name: 'PreviewPage',
    query: {
      template_id: item.id,
      advertiser_id: item.adv_lib_id,
      video_id: item.video_site_id,
      image_id: item.picture_site_id,
      article_id: item.article_site_id
    }
  })
  storage.set('style_data', item.data)
}
//创建副本
const createCopy = (record: TemplateItem) => {
  createVisible.value = true
  const { name, ...params } = record
  Object.assign(formState, params)
}
//弹窗关闭事件
const handleEditClose = () => {
  let key: keyof IFormState
  for (key in formState) {
    formState[key] = undefined
  }
  console.log('formState: ', formState)
}
/**
创建副本对话框事件
 */
const createConfirm = (value: any) => {
  console.log('value: ', value, formState)
  formRef.value.validate().then(() => {
    published_create(formState).then(() => {
      createVisible.value = false
      message.success('模板创建成功')
      emit('update-list')
    })
  })
}
const createCancel = () => {
  createVisible.value = false
}
</script>

<style lang="less" scoped>
.menu-popover {
  width: 120px !important;
  padding: 8px 0 !important;
  .ant-popover-content {
    width: 120px !important;
    .ant-popover-inner {
      width: 120px;
      .ant-popover-inner-content {
        width: 120px;
        height: 136px;
        padding: 8px 0;
        div {
          width: 88px;
          height: 40px;
          line-height: 40px;
          color: #0083ff;
          cursor: pointer;
        }
      }
    }
  }
}
.page-module {
  padding: 32px 0;
  .card {
    border: 1px solid #e8e8e8;
    background-color: #fdfefe;

    .preview {
      display: none;
      text-align: center;
      line-height: 26px;
    }
  }
  .card:hover {
    box-shadow: 12px 8px 44px -12px rgba(27, 58, 146, 0.26);
  }
  .card:hover .preview {
    display: block;
  }
  .activeCss {
    box-shadow: 12px 8px 44px -12px rgba(27, 58, 146, 0.26);
  }
  :deep(.ellipsis-text) {
    max-width: 170px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }
}
</style>
